package com.stu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.commons.ServerResponce;
import com.stu.mapper.CouponMapper;
import com.stu.pojo.Coupon;
import com.stu.pojo.CustomerTokenDTO;
import com.stu.pojo.Mycoupon;
import com.stu.service.ICouponService;
import com.stu.service.IMycouponService;
import com.stu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/coupon")
public class CouponController {
    @Autowired
    private ICouponService iCouponService;
    @Autowired
    private RedisTemplate redisTemplate;
    private DefaultRedisScript<Long> script;  // 定义lua脚本
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private IMycouponService iMycouponService;

    @PostConstruct
    public void init() {
        script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("niceyoo.lua")));
    }

    //添加优惠券
    @PostMapping("insert")
    public ServerResponce insertCoupon(@RequestBody Coupon coupon) {
        ServerResponce responce = iCouponService.insertCoupon(coupon);
        return responce;
    }

    //页面优惠券
    @GetMapping("getAllCoupon")
    public List<Coupon> getCoupon() {
        List<Coupon> result = iCouponService.getAll();
        Map<String, Object> map = new HashMap<>();
        return result;
    }

    //抢购优惠券
    @GetMapping("selectById/{id}")
    public ServerResponce selectCoupon(@PathVariable("id") Integer couponId) {
        Map<String, Object> map = iCouponService.selectByIdCoupon(couponId);
        if (map.get("key") != null) {
            return ServerResponce.success("从缓存当中拿到优惠券", map);
        }
        return ServerResponce.fail("从数据库当中拿到优惠券", map);
    }

    @PostMapping("selectCoupon/{id}")
    public Map<String, Object> selectByIdCoupon(@PathVariable("id") Integer couponId, HttpServletRequest request) {
        // 获取Token并解析
        String token = request.getHeader("Authorization");
        System.out.println("token:" + token);

        String realToken = token.substring(7);
        String userId = JwtUtil.getUserIdFromToken(realToken);  // JwtUtil获取用户ID
//        userId = request.getHeader("userId");

        System.out.println("userId:" + userId);
        Integer custId = Integer.parseInt(userId);  // 转换为Integer类型

        // 获取锁
        String key = "Coupon_" + couponId;
        HashMap<String, Object> map = new HashMap<>();
        String s = UUID.randomUUID().toString().replace("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("key", s, 3, TimeUnit.SECONDS);
        System.out.println("抢优惠券是否获取锁：" + flag);

        // 判断是否获取锁
        if (flag) {
            // 获取到锁则去获得优惠券库存
            Integer count = (Integer) redisTemplate.opsForValue().get(key);
            if (count == 0) {
                map.put("result", "库存不足");
                map.put("key", 0);
                return map;
            }
            count = count - 1;
            System.out.println(count);
            redisTemplate.opsForValue().set(key, count);

            // 同步数据库数据
            Integer integer = iCouponService.updataCoupon(iCouponService.getById(couponId));
            if (integer > 0) {
                System.out.println("修改数据库成功");

                // 创建Mycoupon
                Mycoupon mycoupon = new Mycoupon();
                QueryWrapper<Coupon> wrapper = new QueryWrapper<>();
                wrapper.eq("coupon_id", couponId);
                Coupon coupon = couponMapper.selectOne(wrapper);
                mycoupon.setMycouponNumber(UUID.randomUUID().toString());
                mycoupon.setMycouponStatus(1);
                mycoupon.setMycouponGetTime(LocalDate.now());
                mycoupon.setCouponId(couponId);
                mycoupon.setXx(coupon.getCouponEndTime().toString());
                mycoupon.setYy(coupon.getCouponRule());
                mycoupon.setUserId(custId);
                mycoupon.setMycouponPrice(coupon.getCouponPrice());
                Integer insert = iMycouponService.insert(mycoupon);
                System.out.println(mycoupon);
            }

            // 释放锁
            Long execute = (Long) redisTemplate.execute(script, Arrays.asList("key"), s);
            System.out.println("execute:" + execute);
        } else {
            try {
                Thread.sleep(1000);
                selectByIdCoupon(couponId, request);
                System.out.println("获取锁失败，再次发起请求");
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
        }
        map.put("result", "优惠卷领取成功");
        return map;
    }
}
